const { getApps, getAppsSortedByRating, getAppsSortedByDownloads } = require('../../data/getApps')
const { getUseMock, setUseMock } = require('../../utils/env')
const { isLoggedIn, getToken, logout } = require('../../data/auth')

Page({
  data: {
    useMock: getUseMock(),
    list: [],
    loading: false,
    error: '',
    skeleton: new Array(6).fill(0),
    isLoggedIn: false,
    username: ''
  },

  onLoad() { 
    this.checkLoginStatus()
    this.loadData() 
  },

  onShow() {
    // 每次显示页面时检查登录状态
    this.checkLoginStatus()
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const loggedIn = isLoggedIn()
    const username = wx.getStorageSync('username') || ''
    this.setData({ 
      isLoggedIn: loggedIn,
      username: username
    })
  },

  /**
   * 退出登录
   */
  onLogout() {
    wx.showModal({
      title: '提示',
      content: '确认退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          logout()
          this.setData({ 
            isLoggedIn: false,
            username: ''
          })
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          })
        }
      }
    })
  },

  onPullDownRefresh() {
    this.loadData().finally(() => wx.stopPullDownRefresh())
  },

  onToggleMock(e) {
    const v = !!e.detail.value
    setUseMock(v)
    this.setData({ useMock: v })
    this.loadData()
  },

  async loadData() {
    this.setData({ loading: true, error: '' })
    try {
      const list = await getApps()
      this.setData({ list })
    } catch (e) {
      this.setData({ error: e.message || '加载失败' })
    } finally {
      this.setData({ loading: false })
    }
  },

  async onSortByRating() {
    this.setData({ loading: true, error: '' })
    try {
      const list = await getAppsSortedByRating()
      this.setData({ list })
    } catch (e) {
      this.setData({ error: e.message || '加载失败' })
    } finally {
      this.setData({ loading: false })
    }
  },

  async onSortByDownloads() {
    this.setData({ loading: true, error: '' })
    try {
      const list = await getAppsSortedByDownloads()
      this.setData({ list })
    } catch (e) {
      this.setData({ error: e.message || '加载失败' })
    } finally {
      this.setData({ loading: false })
    }
  }
})
